/*
 * Copyright (c) 2018 Hitevision
 */

package tw.com.hitevision.whiteboard.android.receivers;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import java.util.List;

import tw.com.hitevision.whiteboard.android.MainActivity;
import tw.com.hitevision.whiteboard.android.R;
import tw.com.hitevision.whiteboard.android.util.ActivityUtils;

public class WhiteboardBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = WhiteboardBroadcastReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        log("onReceive: intent=" + intent + ",time="+System.currentTimeMillis());
        log("- action=" + action);
        if (action == null) {
            return;
        }

        final Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        if (action.equals(context.getString(R.string.broadcast_action_start_annotation_mode))) {
            // start annotation mode
            i.putExtra(MainActivity.EXTRA_ANNOTATION_MODE, true);
            i.putExtra(MainActivity.EXTRA_HIDE_APP, false);

        } else if (action.equals(context.getString(R.string.broadcast_action_exit_annotation_mode))) {
            // exit annotation mode
            i.putExtra(MainActivity.EXTRA_ANNOTATION_MODE, false);
            i.putExtra(MainActivity.EXTRA_HIDE_APP, true);

        } else if (action.equals(context.getString(R.string.broadcast_action_start_whiteboard_mode))) {
            // start whiteboard mode
            i.putExtra(MainActivity.EXTRA_ANNOTATION_MODE, false);
            i.putExtra(MainActivity.EXTRA_HIDE_APP, false);

        } else if (action.equals(context.getString(R.string.broadcast_action_end_meeting))) {
            // quit app

            // check if activity is running, either foreground or background
            final List<ActivityManager.RunningTaskInfo> tasks = ActivityUtils.getRunningTasks(context, 10);
            boolean found = false;
            for (ActivityManager.RunningTaskInfo task : tasks) {
                if (task.topActivity.getPackageName().equals(context.getPackageName())) {
                    found = true;
                    break;
                }
            }

            log("found in receiver:"+found);
            if (!found) {
                // The whiteboard activity is not running.  Do nothing since starting the activity
                // just to end it will not work.
                return;
            }

            i.putExtra(MainActivity.EXTRA_END_MEETING, true);
        }

        context.startActivity(i);
    }

    private static void log(String msg) {
        Log.d(TAG, msg);
    }
}
